package com.spring.sample.conf;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;


@Configuration
@EnableTransactionManagement
public class SpringJdbcConf {
	
	
	@Autowired DataSource dataSource;
	@Autowired SqlSessionFactory sqlSessionFactory;

	@Bean
	public SqlSessionTemplate sqlSession(){
		SqlSessionTemplate ss = new SqlSessionTemplate(sqlSessionFactory);
		return ss;
	}
	
	@Bean 
	public SqlSessionFactoryBean sqlSessionFactory(){
		SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
		sf.setDataSource(dataSource);
		Resource[] mapperLocations = new Resource[]{new ClassPathResource("/mapper/compare.sql.xml")};
		sf.setMapperLocations(mapperLocations);
		return sf;
	}
	
	@Bean 
	public DataSourceTransactionManager txManager(){
		DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
		dataSourceTransactionManager.setDataSource(dataSource);
		return dataSourceTransactionManager;
	}
	
	@Bean
	public BasicDataSource dataSource(){
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
		basicDataSource.setUrl("jdbc:oracle:thin:@52.10.4.92:1521:ORCL");
		basicDataSource.setUsername("test_03");
		basicDataSource.setPassword("password_03");
		basicDataSource.setConnectionInitSqls(getSqlList());
		basicDataSource.setInitialSize(2);
		basicDataSource.setMaxActive(30);
		basicDataSource.setMaxIdle(20);
		basicDataSource.setMinIdle(2);
		return basicDataSource;
	}

	private List<String> getSqlList() {
		List<String>sqlList = new ArrayList<String>();
		sqlList.add("select 1 from dual");
		return sqlList;
	}

}
